package com.FrameWork.DB;

import com.FrameWork.Synchoronization.SyncModel;
import com.FrameWork.Synchoronization.SynchConfig;
import com.SFA.R;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

/**
 * @author steven.jiang
 * 
 */
public class DataProvider extends SQLiteOpenHelper
{
	/** The name of the database file on the file system */
	private static final String DATABASE_NAME    = "SFA";
	/** The version of the database that this class understands. */
	private static final int    DATABASE_VERSION = 59;
	public SQLiteDatabase myDataBase;  
	/** Keep track of context so that we can load SQL from string resources */
	private final Context       mContext;

	public void openDataBase() throws SQLException{        
		//Open the database        
		myDataBase =this.getWritableDatabase();//  SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

	} 



	/** Constructor */
	private DataProvider(Context context)
	{
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.mContext = context;

	}

	private static DataProvider provider = null;
	public static DataProvider Instance(Context context)
	{
		if(provider == null)
			provider = new DataProvider(context);
		return  provider;
	}

	public android.database.sqlite.SQLiteCursor Query(String SQL)
	{
		// getDB();
		if(myDataBase ==null || !myDataBase.isOpen())
		{
			openDataBase();
		}
		SQLiteCursor cursor = (android.database.sqlite.SQLiteCursor) myDataBase.rawQuery(SQL,
				null);

		return cursor;
	}

	// /执行SQL语句
	public void Execute(String SQL)
	{
		if(myDataBase ==null || !myDataBase.isOpen())
		{
			openDataBase();
		}
		myDataBase.compileStatement(SQL);
		myDataBase.execSQL(SQL);
		//db.close();
	}

	// 数据库更新操作
	public int Update(String table,
			ContentValues values,
			String whereClause,
			String[] whereArgs)
	{
		if(myDataBase ==null || !myDataBase.isOpen())
		{
			openDataBase();
		}
		int num = myDataBase.update(table, values, whereClause, whereArgs);

		return num;
	}

	// 数据库数据插入操作
	public long
	Insert(String table, String nullColumnHack, ContentValues values)
	{
		SQLiteDatabase db = getWritableDatabase();
		/*long num = db.insertWithOnConflict(table,
				nullColumnHack,
				values,
				SQLiteDatabase.CONFLICT_IGNORE);*/
		long num = db.insertWithOnConflict(table,
				nullColumnHack,
				values,db.CONFLICT_IGNORE);
		// db.close();

		return num;
		// return db.insert(table, nullColumnHack, values);
	}

	public void Execute(String SQL, Object[] bindArgs)
	{
		if(myDataBase ==null || !myDataBase.isOpen())
		{
			openDataBase();
		}

		myDataBase.execSQL(SQL, bindArgs);

	}

	public SQLiteStatement  CompileStatement(String SQL)
	{
		if(myDataBase ==null || !myDataBase.isOpen())
		{
			openDataBase();
		}

		return myDataBase.compileStatement(SQL);

	}

	public android.database.sqlite.SQLiteCursor
	getCursor(String TableName,
			String[] columns,
			String selection,
			String[] selectionArgs,
			String groupBy,
			String having,
			String orderBy)
	{
		if(myDataBase ==null || !myDataBase.isOpen())
		{
			openDataBase();
		}
		return (android.database.sqlite.SQLiteCursor) myDataBase.query(TableName,
				columns,
				selection,
				selectionArgs,
				groupBy,
				having,
				orderBy);
		
	}

	/**
	 * Execute all of the SQL statements in the String[] array
	 * 
	 * @param db
	 *            The database on which to execute the statements
	 * @param sql
	 *            An array of SQL statements to execute
	 */
	private void execMultipleSQL(SQLiteDatabase db, String[] sql)
	{
		for (String s : sql)
			if (s.trim().length() > 0)
				db.execSQL(s);
	}

	/** Called when it is time to create the database */
	@Override
	public void onCreate(SQLiteDatabase db)
	{
		String[] sql = mContext.getString(R.string.DB_INSERT).split(";");
		db.beginTransaction();
		try
		{
			// Create tables & test data
			execMultipleSQL(db, sql);
			db.setTransactionSuccessful();
			//set sync model= full sync
			SynchConfig config = SynchConfig.Instance(mContext);
			config.setSyncModel(SyncModel.InitialSync);
			try {
				config.Save();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		catch (SQLException e)
		{
			Log.e("Error creating tables and debug data", e.toString());
		}
		finally
		{
			db.endTransaction();
		}

	}

	/** Called when the database must be upgraded */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		Log.w("DBLOG", "Upgrading database from version "
				+ oldVersion
				+ " to "
				+ newVersion
				+ ", which will destroy all old data");

		String[] sql = mContext.getString(R.string.DB_UPGRADE).split(";");
		db.beginTransaction();

		try
		{
			for(String str:sql)
			{
				try
				{
					// Create tables & test data
					db.execSQL(str);
					//execMultipleSQL(db, sql);
				}
				catch(Exception err)
				{
					err.printStackTrace();
				}

			}
			db.setTransactionSuccessful();
		}
		catch (SQLException e)
		{
			if(e!= null)
				Log.e("Error creating tables and debug data", e.toString());
		}
		finally
		{
			db.endTransaction();
		}

		// This is cheating. In the real world, you'll need to add columns, not
		// rebuild from scratch
		onCreate(db);
	}

}
